package com.ovo.chatRobot.utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.iflytek.cloud.speech.RecognizerListener;
import com.iflytek.cloud.speech.RecognizerResult;
import com.iflytek.cloud.speech.SpeechConstant;
import com.iflytek.cloud.speech.SpeechError;
import com.iflytek.cloud.speech.SpeechRecognizer;
import com.iflytek.cloud.speech.SpeechUtility;

@Component
public class VoiceToText {	
	@Autowired
    private RedisTemplate redisTemplate;
	public StringBuffer listeningBuffer = new StringBuffer();
	public void init() {
		System.out.println("*******初始化语音监听***************");
		// 初始化
		SpeechUtility.createUtility("appid=" + Utils.getAppid());
		// 1.创建SpeechRecognizer对象
		SpeechRecognizer mIat = SpeechRecognizer.createRecognizer();
		// 2.设置听写参数，详见《MSC Reference Manual》 SpeechConstant类
		mIat.setParameter(SpeechConstant.DOMAIN, "iat");
		mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
		mIat.setParameter(SpeechConstant.ACCENT, "mandarin ");
		// 3.开始听写
		mIat.startListening(mRecoListener);			
		TextToVoice.init();

	}
	
	//获取语音识别结果
	public String getVoiceText() {
		return listeningBuffer.toString();
	}

	// 听写监听器
	private RecognizerListener mRecoListener = new RecognizerListener() {
		// 听写结果回调接口(返回Json格式结果，用户可参见附录)；
		// 一般情况下会通过onResults接口多次返回结果，完整的识别内容是多次结果的累加；
		// 关于解析Json的代码可参见MscDemo中JsonParser类；
		// isLast等于true时会话结束。
		public void onResult(RecognizerResult results, boolean isLast) {
			try {
				JSONObject jason = new JSONObject(results.getResultString());
				String sn=jason.getString("sn");  //第几句
				 String ls=jason.getString("ls");  //是否最后一句
//				 String bg=jason.getString("bg");  //开始
//				 String ed=jason.getString("ed");  //结束
				 String ws=jason.getString("ws");  //词
//				 String cw=jason.getString("cw");  //中文分词
//				 String w =jason.getString("w");  //单字
//				 String sc=jason.getString("sc");  //分数
				 System.out.println(isLast+"你说："+results.getResultString());
				 if(!isLast) {
					 String str = ws.substring(1,ws.length()-1);
						String[]arr= str.split("\"w\":");
						StringBuffer buffer2 = new StringBuffer();
						for(int i=1;i<arr.length;i++) {
							buffer2.append(arr[i].substring(1, arr[i].indexOf("\"", 1)));
						}
					 listeningBuffer.append(buffer2.toString());
					 String listeningWords = listeningBuffer.toString();					 
					 if(null!=listeningWords&&(!"".equals(listeningWords))) {
						 listeningBuffer.delete(0, listeningWords.length());
						 String backWords = Tuling.SendPost(listeningWords);
						 System.out.println("图灵机器人说："+backWords);
						 redisTemplate.opsForValue().set("req_words",listeningWords);
						 redisTemplate.opsForValue().set("rep_words",backWords);
						 Thread.sleep(200);
						 TextToVoice.toSpeaking(backWords);
						 
					}
				 }	
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// 会话发生错误回调接口
		public void onError(SpeechError error) {
			error.getErrorDescription(true); // 获取错误码描述
		}

		// 开始录音
		public void onBeginOfSpeech() {
		}

		// 音量值0~30
		public void onVolumeChanged(int volume) {
		}

		// 结束录音
		public void onEndOfSpeech() {
		}

		// 扩展用接口
		public void onEvent(int eventType, int arg1, int arg2, String msg) {
		}
	};

}
